<?php
namespace app\common\controller;
use think\Db;
//创建和更新需要初始化对应的model文件(model 内部不需要写东西)
//作为此控制器增删改查的主表，默认表名对应该控制器，可自定义表名
//当一个控制器一张主表不满足时，可以自定义config里的参数 做出无数张表。
class Curd extends Base
{
    protected $total = null;
    protected function _initialize(){
        parent::_initialize();
    }
    //日志
    //自动部分开关及存入仅限于增删改查
    //写日志
    protected function logIns($action,$content,$result,$table=''){
        $request = $this->request;
        $ip = $request->ip();
        $arr = [];
        if(!empty($this->admin)&&$this->admin){
            $arr['operator'] = $this->admin['admin_nickname'];
            $arr['operator_id'] = $this->admin['id'];
        }
        $arr['action'] = $action;
        $arr['ip'] = $ip;
        $arr['result'] = $result;
        if($table){
            $arr['table_log'] = $table;
        }
        else{
            $arr['table_log'] = $this->table;
        }
        $arr['content'] = encode($content);
        $create = model('curd_log');
        $create->allowField(true)->save($arr);
    }
    //读日志
    protected function logRead($where = [],$page=1,$size=15,$order = 'id desc'){
        $res = Db::connect('db_log')
            ->name($this->table . '_log')
            ->where($where)->order($order)->page($page,$size)
            ->select();
        return $res;
    }
    //数据量
    protected function count($where = [],$is_delete=[]){
        if($is_delete==0){
            $is_delete = ['is_delete'=>0];
        }
        if($is_delete==1){
            $is_delete = ['is_delete'=>1];
        }
        $res = Db::name($this->table)->where($is_delete)->where($where)->count();
        return $res;
    }

    public function select($where = [],$order = 'sort desc,id desc'){
        if(!$this->privilege['read']){
            return json(['code'=>0,'msg'=>'暂无权限！','data'=>[]]);
        }
        if($this->count($where,0)>100){
            $data = ['code'=>0,'msg'=>'请求数据数量过多！','data'=>[]];
        }
        else{
            $res = Db::name($this->table)->where('is_delete',0)
                ->where($where)->order($order)->field($this->field[0],$this->field[1])->select();
            if($res){
                $data = ['code'=>1,'msg'=>'success','data'=>$res];
            }
            else{
                $data = ['code'=>0,'msg'=>'fail'];
            }
        }
        return json( $data );
    }
    //分页
    public function page( $page = 1,$size = 15 ,$where=[],$order = 'create_time desc,id desc'){
        if(!$this->privilege['read']){
            return json(['code'=>0,'msg'=>'暂无权限！','data'=>[]]);
        }
        if($size>100){
            $data = ['code'=>0,'msg'=>'请求数据数量过多！'];
        }
        else{
            $res = Db::name($this->table)->where('is_delete',0)->where($where)
                ->field($this->field[0],$this->field[1])->order($order)->page($page,$size)->select();
            $data = [
                'code' => 1,
                'msg' => 'success',
                'data' => $res,
                'total' => $this->count($where,0),
                'page' => $page,
                'size' => $size
            ];
        }
        return json( $data );
    }
    //查单个
    public function read( $id = null,$where=[]){
        if(!$this->privilege['read']){
            return json(['code'=>0,'msg'=>'暂无权限！','data'=>[]]);
        }
        if(isset( $id )){
            $res = Db::name($this->table)->where(['id'=>$id,'is_delete'=>0])->where($where)->
            field($this->field[0],$this->field[1])->find();
            if($res){
                $data =['code'=>1,'msg'=>'success','data'=>$res];
            }
            else{
                $data = ['code'=>0,'msg'=>'fail'];
            }
        }
        else{
            $data = ['code'=>0,'msg'=>'缺少参数'];
        }
        return json( $data );
    }
    //增
    public function create($params = []){
        if(!$this->privilege['create']){
            return json(['code'=>0,'msg'=>'暂无权限！','data'=>[]]);
        }
        $create =  model($this->table);
        $create->allowField(true)->save($params);
        $arr =  decode( $create );
        if(isset($arr['id']) == true){
            $row = ['code'=>1,'msg'=>'添加成功！','data'=>[]];
            if($this->is_log){
                $log_res = $this->read($arr['id']);
                $this->logIns('create',obj_decode($log_res)['data'],1);
            }
        }
        else{
            $row = ['code'=>0,'msg'=>'添加失败！','data'=>[]];
            if($this->is_log){
                $params['id'] = 'fail';
                $this->logIns('create',$params,0);
            }
        }
        return json( $row );
    }
    //改
    public function update($params=[]){
        if(!$this->privilege['update']){
            return json(['code'=>0,'msg'=>'暂无权限！','data'=>[]]);
        }
        $fixed = $this->fixed;
        if(isset($params['id'])){
            $id = $params['id'];
            unset($params['id'],$params['is_delete']);
            foreach ($fixed as $v){
                if(isset($params[$v])){
                    unset($params[$v]);
                }
            }
            if($this->is_log){
                $old_data =  $this->read($id);
                $old_data = obj_decode($old_data)['data'];
            }
            $edit = model($this->table);
            $edit->allowField(true)->save($params,['id'=>$id]);
            if($this->is_log){
                $new_data = $this->read($id);
                $new_data = obj_decode($new_data)['data'];
                $this->logIns('update',['old_data'=>$old_data,'update_data'=>$new_data],1);
            }
            $row = ['code'=>1,'msg'=>'更新成功！','data'=>[]];
            return json( $row );
        }
        else{
            return json(['code'=>0,'msg'=>'参数缺失！']);
        }
    }
    //删(非真实删除)
    public function delete( $id = null){
        if(!$this->privilege['delete']){
            return json(['code'=>0,'msg'=>'暂无权限！','data'=>[]]);
        }
        if(isset( $id )){
            $idArr = explode(',',$id);
            if($this->is_log){
                dump(1);
                $delete_data = $this->select(['in',$idArr]);
                dump($delete_data);
            }
            $delete = Db::name($this->table)->whereIn('id',$idArr)->update(['is_delete'=>1]);
            if($delete){
                $res = ['code'=>1,'msg'=>'删除成功！','data'=>[]];
                if($this->is_log){
                    $this->logIns('delete',$delete_data,1);
                }
            }
            else{
                $res = ['code'=>0,'msg'=>'删除失败！','data'=>[]];
                if($this->is_log){
                    $this->logIns('delete',$delete_data,0);
                }
            }
        }
        else{
            $res = ['code'=>0,'msg'=>'缺少参数！','data'=>[]];
        }
        return json( $res );
    }
    //递归删除
    public function redelete( $id = null){
        if(!$this->privilege['delete']){
            return json(['code'=>0,'msg'=>'暂无权限！','data'=>[]]);
        }
        if(isset( $id )){
            $idArr = explode(',',$id);
            $arr = $this->sqlGetSon($idArr);
//            exit( encode( $arr ));
            $str = join(',',$arr);
            $delete = Db::name($this->table)->whereIn('id',$arr)->update(['is_delete'=>1]);
            $params = [];$params['id'] = $str;
            if($delete){
                $res = ['code'=>1,'msg'=>'删除成功！','data'=>[]];
                if($this->is_log){
                    $this->logIns('delete',$params,1);
                }
            }
            else{
                $res = ['code'=>0,'msg'=>'删除失败！','data'=>[]];
                if($this->is_log){
                    $this->logIns('delete',$params,0);
                }
            }
        }
        else{
            $res = ['code'=>0,'msg'=>'缺少参数！','data'=>[]];
        }
        return json( $res );
    }
    private function sqlGetSon($idArr){
        static $child = [];
        foreach ($idArr as $k=>$v){
            array_push($child,$v);
            $children = Db::name($this->table)->whereIn('pid',$v)->select();
            if($children){
                $arr = [];
                foreach ($children as $k1=>$v1){
                    array_push($arr,$v1['id']);
                }
                $this->sqlGetSon($arr);
            }
        }
        return $child;
    }
    //回收站内容
    public function recycle( $page = 1,$size = 15,$where=[],$order = 'create_time desc,id'){
        //存在问题；
        if(!$this->privilege['delete']){
            return json(['code'=>0,'msg'=>'暂无权限！','data'=>[]]);
        }
        $total = $this->count($where,1);
        if($size>100){
            $data = ['code'=>0,'msg'=>'请求数据数量过多！'];
        }
        else{
            $res = Db::name($this->table)->where('is_delete',1)->where($where)->
            field($this->field[0],$this->field[1])->order($order)
                ->page($page,$size)->select();
            $data = [
                'code' => 1,
                'msg' => 'success',
                'data' => $res,
                'total' =>$total,
                'page' => $page,
                'size' => $size
            ];
        }
        return json( $data );
    }
    //还原数据（回收站）
    public function reduction( $id = null ){
        if(!$this->privilege['delete']){
            return json(['code'=>0,'msg'=>'暂无权限！','data'=>[]]);
        }
        if(isset( $id )){
            $idArr = explode(',',$id);
            $data = Db::name($this->table)->whereIn('id',$idArr)->update(['is_delete'=>0]);
            $params = [];$params['id'] = $id;
            if($data){
                $res = ['code'=>1,'msg'=>'还原成功!','data'=>[]];
                if($this->is_log){
                    $this->logIns('reduction',$params,1);
                }
            }
            else{
                $res = ['code'=>0,'msg'=>'还原失败!','data'=>[]];
                if($this->is_log){
                    $this->logIns('reduction',$params,0);
                }
            }
        }
        else{
            $res = ['code'=>0,'msg'=>'缺少参数!','data'=>[]];
        }
        return json( $res );
    }
    //删除回收站
    public function cleanUp( $id = null ){
        if(!$this->privilege['delete']){
            return json(['code'=>0,'msg'=>'暂无权限！','data'=>[]]);
        }
        $params = [];
        if(isset( $id )){
            if($id=='all'){
                $del = Db::name($this->table)->where('is_delete',1)->select();
                $arr = [];
                foreach ($del as $v){
                    array_push($arr,$v['id']);
                }
                $id_log = implode(',',$arr);
                $params['id'] = $id_log;
                $delete = Db::name($this->table)->where('is_delete',1)->delete();
            }
            else{
                if($this->is_log){
                    $params['id'] = $id;
                }
                $idArr = explode(',',$id);
                $delete = Db::name($this->table)->where('is_delete',1)->
                whereIn('id',$idArr)->delete();
            }

            if($delete){
                $res = ['code'=>1,'msg'=>'销毁成功!','data'=>[]];
                if($this->is_log){
                    $this->logIns('cleanUp',$params,1);
                }
            }
            else{
                $res = ['code'=>0,'msg'=>'销毁失败!','data'=>[]];
                if($this->is_log){
                    $this->logIns('cleanUp',$params,0);
                }
            }
        }
        else{
            $res = ['code'=>0,'msg'=>'缺少参数!','data'=>[]];
        }
        return json( $res ) ;
    }
    //获取用户信息
    public function userinfo(){
        $params = $this->params;
        //如果存在token就为cache否则session
        if(isset($params['token'])){
            $data = ['code'=>0,'msg'=>'cache登陆尚未开通'];
        }
        else{
            if(isset($this->session['admin'])){
                $admin = $this->session['admin'];
                unset($admin['admin_privilege']);
                $data = ['code'=>1,'msg'=>'获取成功！','data'=>$admin];
            }
            else{
                $data = ['code'=>0,'登录超时！'];
            }
        }
        return json( $data );
    }
    //是否登录||框架外使用;
    public function is_login(){
        $params = $this->params;
        //如果存在token就为cache否则session
        if(isset($params['token'])){
            $data = ['code'=>0,'msg'=>'cache登陆尚未开通'];
        }
        else{
            if(isset($this->session['admin'])){
                $data = ['code'=>1,'msg'=>'已登录！'];
            }
            else{
                $jump = '/admin/member/login?refer=' . $params['url'];
                $data = ['code'=>0,'msg'=>'登录超时！','jump'=>$jump];
            }
        }
        return json( $data );
    }
    //获取配置表
    public function systemConfig(){
        $data =  $this->system;
        return json($data);
    }

}